﻿using AutoMapper;
using MediatR;
using SmartTracking.API.Read.Application.Commands.User_command;
using SmartTracking.API.Read.DTO;
using SmartTracking.Domain.UserInfo;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace SmartTracking.API.Read.Application.CommandHandlers.User_handler
{
    public class GetUserCommandHandler : IRequestHandler<GetUserCommand, ApiResult<ApiPaging<UserDto>>>
    {
        private readonly IBaseRepository<Users> userRep;
        private readonly IBaseRepository<Roles> roleRep;
        private readonly IBaseRepository<UserRoleMiddle> urRep;
        private readonly IMapper mapper;

        public GetUserCommandHandler(
            IBaseRepository<Users> userRep,
            IBaseRepository<Roles> roleRep,
            IBaseRepository<UserRoleMiddle> urRep,
            IMapper mapper)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.urRep = urRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<ApiPaging<UserDto>>> Handle(GetUserCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<UserDto>> result = new ApiResult<ApiPaging<UserDto>>();
            result.Code = ApiEnum.查询成功;
            result.Message = ApiEnum.查询成功.ToString();

            //获取未删除的用户信息
            var users = userRep.GetAll().Where(x => x.IsDeleted == false);
            var userlist = mapper.Map<List<UserDto>>(users);
            //循环获取用户角色
            foreach (var item in userlist)
            {
                //用户角色中间表 现获取用户ID 筛选出角色
                var userroles = urRep.GetAll().Where(x => x.UserId == item.UserId).Select(x => x.RoleId).ToList();
                item.RoleId = userroles;
                //根据角色ID 获取角色名称 循环出来 模糊查询
                var roles = roleRep.GetAll().Where(x => userroles.Contains(x.RoleId)).Select(x => x.RoleName).ToList();
                item.RoleName = roles;
            }
            if (!string.IsNullOrEmpty(request.UserNickName))
            {
                userlist = userlist.Where(x => x.UserNickName.Contains(request.UserNickName)).ToList();
            }
            if(request.UserStatus != 0)
            {
                userlist = userlist.Where(x => x.UserStatus == request.UserStatus).ToList();
            }

            int ListCount = userlist.Count();
            int PageCount = (int)Math.Ceiling(ListCount * 1.0 / request.PageSize);
            userlist = userlist.OrderByDescending(x => x.UserId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();

            ApiPaging<UserDto> paging = new ApiPaging<UserDto>();
            paging.totalCount = ListCount;
            paging.totalPage = PageCount;
            paging.data = userlist.ToList();

            result.data = paging;
            return Task.FromResult(result);
        }
    }
}
